package com.my.blog.myblog.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.blog.annotation.SystemLog;
import com.my.blog.myblog.entity.Bloger;
import com.my.blog.myblog.mapper.BlogerMapper;
import com.my.blog.myblog.service.BlogerService;
import com.my.blog.utils.ConstantUtil;
import com.my.blog.utils.ResultBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/***
 *
 * @Auther: MuYun
 * @Date: 2021/8/30 21:41
 * @Description： shiro的controller，也就是认证和未授权的跳转
 *
 */
@RestController
public class LoginController {

    private Logger logger= LoggerFactory.getLogger(this.getClass());


    @Resource
    BlogerService blogerService;

    @GetMapping("/unauthorized")
    public ResultBean<Object> unauth(){
        ResultBean<Object> resultBean=new ResultBean<>();
        resultBean.setCode(300);
        resultBean.setMsg("抱歉，您没有此权限");
        return resultBean;
    }

    @PostMapping("/doLogin")
    @SystemLog(description = ConstantUtil.LOGIN_IN)
    public ResultBean<Object> login(@RequestParam(value = "username") String username,
                                    @RequestParam(value = "password") String password
                                    ){
        ResultBean<Object> resultBean=new ResultBean<>();
        QueryWrapper<Bloger> wrapper=new QueryWrapper<>();
        Bloger one = blogerService.getOne(wrapper.lambda().eq(Bloger::getUsername, username));
        if(ObjectUtil.isEmpty(one)){
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setMsg("用户名不存在！");
            return  resultBean;
        }
        // md5加盐加密: md5(md5(str) + md5(salt))
        String mdPassword = SaSecureUtil.md5BySalt(password, username);
        logger.info("加盐加密后的密码：{}",mdPassword);
        logger.info("数据库密码：{}",one.getPassword());
        if(!one.getPassword().equals(mdPassword)){
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setMsg("密码错误！");
            return  resultBean;
        }
        //非记住我登陆，否则登陆日志将记录不全
        StpUtil.login(one.getId(),false);


        if(!StpUtil.isLogin()){
            resultBean.setCode(403);
            resultBean.setMsg("您还未登陆");
        }

        return  resultBean;
    }

}
